package com.dq.controller.goods.stock;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.dq.controller.in.goods.stock.OrgGoodsAndStockQuery;
import com.dq.controller.in.goods.stock.OrgGoodsCentreQuery;
import com.dq.domain.org.Org;
import com.dq.exception.customException.AdminException;
import com.dq.controller.in.goods.BossGoodsQuery;
import com.dq.controller.op.opmerchant.in.request.GoodRequest;
import com.dq.controller.op.opmerchant.in.request.GoodSpecificationRequest;
import com.dq.controller.op.opmerchant.in.request.ProductRequest;
import com.dq.vo.ListDataVo;
import com.dq.vo.Vo;
import com.dq.vo.baseVo.VO;
import com.dq.domain.category.Category;


import com.dq.domain.goods.*;
import com.dq.domain.goods.stock.StockChangeRecord;
import com.dq.domain.sys.section.SysSection;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.service.AllService;
import com.dq.service.section.SysSectionService;
import com.dq.utils.BeanNullUtil;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author ----
 * @date 2019/9/2016:31
 */
@Api("商品管理")
@RestController
@RequestMapping("sys/goods/")
public class SysGoodsController extends AllService {
    @Autowired
    private SysSectionService sysSectionService;

    @ApiOperation("所有商品列表-不关联门店, 无库存: [后台商品管理]")
    @PostMapping("list")
    public Vo list(@RequestBody BossGoodsQuery bossGoodsQuery) throws AdminException {
        bossGoodsQuery.format();
        List<Goods> goodsList = goodsService.list(bossGoodsQuery);
        return new ListDataVo((List<Goods.Vo>) VO.toVOCollection(goodsList), goodsService.count(bossGoodsQuery));
    }

    @ApiOperation("所有商品列表-不关联门店, 无库存: [入库登记]")
    @PostMapping("listAll")
    public Vo listAll(@RequestBody BossGoodsQuery bossGoodsQuery) throws AdminException {
        bossGoodsQuery.format();
        bossGoodsQuery.setPage(null);
        bossGoodsQuery.setSize(null);
        if (bossGoodsQuery.getGoodsStatus() == null) {
            bossGoodsQuery.setGoodsStatus(Goods.GoodsStatus.upperShelf);
        }
        List<Goods> goodsList = goodsService.list(bossGoodsQuery);
        return new ListDataVo((List<Goods.Vo>) VO.toVOCollection(goodsList));
    }

    @PostMapping("orgListAndStock")
    @ApiOperation("门店商品列表, 有库存")
    public Vo list(@RequestBody @ApiParam("") OrgGoodsAndStockQuery orgGoodsStockQuery) throws AdminException {

        //判断传参商品状态,如果没有判断成上架状态
        if (orgGoodsStockQuery.getGoodsStatus() == null) {
            orgGoodsStockQuery.setGoodsStatus(Goods.GoodsStatus.upperShelf);
        }

        orgGoodsStockQuery.format();
        ArrayList<Goods.OrgStockListVo> list = new ArrayList<>();
        // 关联门店, 门店ID, 不传默认是登录账号门店下
        long orgId = orgGoodsStockQuery.getOrgId() == null ? sysUserService.getUserInSection().getSection().getId() : orgGoodsStockQuery.getOrgId();
        //获取门店id,如果状态值不为null查询角色下所有门店id
        if (orgGoodsStockQuery.getOrgId()==0){
            //获取该用户下所有的门店
            List<Org> listAllByUser = orgService.getListAllByUser();
            listAllByUser.forEach(x->{
                List<Goods> goods = goodsService.goodsByOrgAndStockList(orgGoodsStockQuery, x.getId(), false);
                goods.forEach(i->{
                    list.add(i.toOrgStockListVo());
                });
            });
            return new ListDataVo(list);
        }
        List<Goods> goodsList = goodsService.goodsByOrgAndStockList(orgGoodsStockQuery, orgId, false);
        for (Goods goods : goodsList) {
            list.add(goods.toOrgStockListVo());
        }

        return new ListDataVo(list, goodsService.goodsByOrgCount(orgGoodsStockQuery, orgId, false));
    }

    @PostMapping("orgList")
    @ApiOperation("门店商品列表, 无库存")
    public Vo orgList(@RequestBody OrgGoodsAndStockQuery orgGoodsAndStockQuery) throws AdminException {
        if (orgGoodsAndStockQuery.getGoodsStatus() == null) {
            orgGoodsAndStockQuery.setGoodsStatus(Goods.GoodsStatus.upperShelf);
        }
        orgGoodsAndStockQuery.format();
        // 关联门店, 门店ID, 不传默认是登录账号门店下
        long orgId = orgGoodsAndStockQuery.getOrgId() == null ? sysUserService.getUserInSection().getSection().getId() : orgGoodsAndStockQuery.getOrgId();

        List<Goods> goodsList = goodsService.goodsByOrgList(orgGoodsAndStockQuery, orgId);

        return new ListDataVo((List<Goods.Vo>) VO.toVOCollection(goodsList), goodsService.goodsByOrgCount(orgGoodsAndStockQuery, orgId, false));
    }

    @PostMapping("orgListAll")
    @ApiOperation("门店商品列表, 无库存: [出库登记]")
    public Vo orgListAll(@RequestBody OrgGoodsAndStockQuery orgGoodsAndStockQuery) throws AdminException {
        if (orgGoodsAndStockQuery.getGoodsStatus() == null) {
            orgGoodsAndStockQuery.setGoodsStatus(Goods.GoodsStatus.upperShelf);
        }
        orgGoodsAndStockQuery.format();
        orgGoodsAndStockQuery.setPage(null);
        orgGoodsAndStockQuery.setSize(null);
        // 关联门店, 门店ID, 不传默认是登录账号门店下
        long orgId = orgGoodsAndStockQuery.getOrgId() == null ? sysUserService.getUserInSection().getSection().getId() : orgGoodsAndStockQuery.getOrgId();

        List<Goods> goodsList = goodsService.goodsByOrgList(orgGoodsAndStockQuery, orgId);

        return new ListDataVo((List<Goods.Vo>) VO.toVOCollection(goodsList));
    }

    @ApiOperation("获取单个商品goods库存")
    @PostMapping("getGoodsStock")
    public Vo getGoodsStock(@ApiParam("只需goodsId参数, orgId不传默认根据登录用户") @RequestBody OrgGoodsAndStockQuery orgGoodsAndStockQuery) throws AdminException {
        if (orgGoodsAndStockQuery.getGoodsId() == null) {
            throw new AdminException("商品ID为空");
        }
        // 关联门店, 门店ID, 不传默认是登录账号门店下
        long orgId = orgGoodsAndStockQuery.getOrgId() == null ? sysUserService.getUserInSection().getSection().getId() : orgGoodsAndStockQuery.getOrgId();
        return new Vo(goodsService.goodsStock(orgGoodsAndStockQuery.getGoodsId(), orgId));
    }


    @ApiOperation("商品详情")
    @PostMapping("get/{goodId}")
    @RequiresPermissions("sys:good:get")
    public VO get(@PathVariable @ApiParam("商品id") Long goodId) throws AdminException {
        SysUser user = sysUserService.getUser();
        if (user.getSection() == null || user.getSection().getId() == null) {
            throw new AdminException("登录账号门店信息获取异常");
        }
        Goods goods = dao.get(Goods.class, goodId);
        if (null == goods) {
            throw new AdminException("商品不存在");
        }
        Goods.OrgStockListVo orgStockListVo = goods.toOrgStockListVo();
        // 库存
        orgStockListVo.setGoodsStock(goodsService.goodsStock(goods.getId(), user.getSection().getId()));
        // SKU
        List<Product> productList = productRepository.findByGoodsAndDeletedFalse(goods);
        String sku = "";
        for (Product product : productList) {
            sku = sku + product.getSku() + ",";
        }
        if (sku.length() > 0) {
            sku = sku.substring(0, sku.length() - 1);
        }
        orgStockListVo.setSku(sku);
        // 分类
        List<Long> categoryIdList = new ArrayList<>();
        if (goods.getCategory() != null) {
            List<Category> parCategoryList = categoryService.getParCategoryList(goods.getCategory().getId());
            for (Category category : parCategoryList) {
                categoryIdList.add(category.getId());
            }
        }
        orgStockListVo.setCategoryIdList(categoryIdList);

        return new Vo(orgStockListVo);
    }

    @ApiOperation("新增商品")
    @PostMapping("add")
    @RequiresPermissions("sys:good:add")
    @Transactional(rollbackFor = Exception.class)
    public VO addGood(@RequestBody GoodRequest goodRequest) throws AdminException {
        SysUser loginUser = sysUserService.getUserInSection();

        Goods goods = new Goods();
        // TODO 注意: 此方法后续不能再次查询goods 对象
        goods = goodsLogic(goodRequest, goods, loginUser);

        goods = goodsService.initObject(goods);

        goods = goodsRepository.save(goods);

        saveProduct(goodRequest.getSku(), goodRequest.getGoodsStock(), goods);
        return new Vo(goods.getId());
    }

    @ApiOperation("编辑商品")
    @PostMapping("update/{goodsId}")
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("sys:good:update")
    public VO updateGood(@RequestBody GoodRequest goodRequest, @PathVariable @ApiParam(value = "商品id") Long goodsId) throws AdminException {
        SysUser loginUser = sysUserService.getUser();
        if (loginUser.getSection() == null || loginUser.getSection().getId() == null) {
            throw new AdminException("登录用户门店信息异常");
        }

        Goods goods = dao.get(Goods.class, goodsId);
        // TODO 注意: 此方法后续不能再次查询goods 对象
        goods = goodsLogic(goodRequest, goods, loginUser);

        goods.setUpdateUser(loginUser);
        // 保存商品
        goods = goodsRepository.save(goods);

        // 获取商品默认 product
        Product product = productRepository.findByGoodsAndDeletedFalseAndIsDefaultTrue(goods);
        if (!product.getSku().equals(goodRequest.getSku())) {
            if (product == null || StringUtils.isEmpty(product.getGoodSpecIds())) {
                throw new AdminException("SKU异常");
            }
            GoodSpecification goodSpecification = dao.get(GoodSpecification.class, new Long(product.getGoodSpecIds()));
            if (goodSpecification == null || goodSpecification.getSpecification() == null) {
                throw new AdminException("SKU异常");
            }
            goodSpecification.setDeleted(true);
            goodSpecificationRepository.save(goodSpecification);
            Specification specification = dao.get(Specification.class, goodSpecification.getSpecification().getId());
            if (specification == null) {
                throw new AdminException("SKU异常");
            }
            specification.setDeleted(true);
            specificationRepository.save(specification);
            GoodSpecification save = save(goodRequest.getSku(), goods);
            product.setSku(goodRequest.getSku());
            product.setGoodSpecIds(save.getId().toString());
            productRepository.save(product);
        }

        // 更新库存, 添加库存变动记录
        updateGoodsByStock(goodRequest.getGoodsStock(), loginUser.getSection(), goods, product);

        return new Vo(HttpStatus.OK);
    }

    /**
     * 更新库存, 添加库存变动记录
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateGoodsByStock(Long stockUpdate, SysSection section, Goods goods, Product product) {
        Long stock = goodsService.productStock(product.getId(), section.getId());
        StockChangeRecord s = new StockChangeRecord();
        s.setOrg(section);
        s.setGoods(goods);
        s.setProduct(product);
        s.setChangeType(StockChangeRecord.ChangeType.adjust);
        s.setStockStatus(StockChangeRecord.StockStatus.ApprovalSuccess);
        if (stock - stockUpdate < 0) {
            s.setChangeDirection(StockChangeRecord.ChangeDirection.add);
            s.setNum(stockUpdate - stock);
            StockChangeRecord stockChangeRecord = orgStockChangeService.saveStockChangeRecord(s, goods, product, section, true);
        } else if (stock - stockUpdate > 0) {
            s.setChangeDirection(StockChangeRecord.ChangeDirection.reduce);
            s.setNum(stock - stockUpdate);
            StockChangeRecord stockChangeRecord = orgStockChangeService.saveStockChangeRecord(s, goods, product, section, true);
        }
    }

    public Goods goodsLogic(GoodRequest goodRequest, Goods goods, SysUser loginUser) {
        // 属性判断
        if (StringUtils.isBlank(goodRequest.getSku())) {
            throw new AdminException("填写SKU");
        }
        if (StringUtils.isEmpty(goodRequest.getGoodsDescription())) {
            throw new AdminException("填写详情");
        }
        if (goodRequest.getIsIntegralGoods()) {
            if (goodRequest.getIntegralNum() == null) {
                throw new AdminException("填写积分");
            }
        }
        if (StringUtils.isBlank(goodRequest.getGoodsNo())) {
            throw new AdminException("填写商品编号");
        }
        Goods goodsNoGoods = goodsRepository.findByDeletedFalseAndGoodsNo(goodRequest.getGoodsNo());
        if (goods.getId() == null) {
            if (goodsNoGoods != null) {
                throw new AdminException("此编号已存在");
            }
        } else {
            if (goodsNoGoods != null && !goodsNoGoods.getId().toString().equals(goods.getId().toString())) {
                throw new AdminException("此编号已存在");
            }
        }

        SysSection loginUserSection = loginUser.getSection();
        if (goodRequest.getOrgId() == null) {
            // 商品默认属于公司
            goodRequest.setOrgId(loginUserSection.getId());
        }

        if (goodRequest.getCategoryIdList() == null || goodRequest.getCategoryIdList().size() <= 0) {
            throw new AdminException("选择分类");
        } else {
            if (goodRequest.getCategoryIdList().size() < 2) {
                throw new AdminException("分类层级小于2");
            }
        }
        // 最后一级分类
        Long categoryId = goodRequest.getCategoryIdList().get(goodRequest.getCategoryIdList().size() - 1);
        Category category = dao.get(Category.class, categoryId);
        if (null == category) {
            throw new AdminException("所选类别不存在");
        }
        if (goods == null) {
            throw new AdminException("未找到此商品");
        }
        BeanUtils.copyProperties(goodRequest, goods, BeanNullUtil.getNullPropertyNames(goodRequest));
        goods.setCategory(category);

        return goods;
    }

    @ApiOperation("上架下架商品")
    @PostMapping("updateStatus/{goodsId}/{goodsStatus}")
    @RequiresPermissions("sys:good:updateStatus")
    public VO updateGood(@PathVariable @ApiParam(value = "商品id") Long goodsId, @PathVariable @ApiParam(value =
            "商品状态") Goods.GoodsStatus goodsStatus) throws AdminException {
        Goods goods = dao.get(Goods.class, goodsId);
        if (goods == null) {
            throw new AdminException("未找到此商品");
        }
        goods.setGoodsStatus(goodsStatus);
        goodsRepository.save(goods);
        return new Vo(HttpStatus.OK);
    }

    /**
     * 商品删除, 删除门店商品关联对象, 生成库存变动记录
     */
    @ApiOperation("删除商品")
    @PostMapping("delete/{goodsId}")
    @RequiresPermissions("sys:good:delete")
    public VO deleteGoods(@PathVariable @ApiParam(value = "商品id") Long goodsId) throws AdminException {
        goodsService.deleteGoods(goodsId);

        return new Vo(HttpStatus.OK);
    }


    @ApiOperation("产品列表")
    @GetMapping("product/list/{goodId}")
    @RequiresPermissions("sys:good:productlist")
    public Vo<Product.Vo> productlist(@PathVariable @ApiParam("产品id") Long goodId) throws AdminException {
        Goods goods = dao.get(Goods.class, goodId);
        if (null == goods) {
            throw new AdminException("商品不存在");
        }
        List<Product> products = productRepository.findByGoodsAndDeletedFalseAndIsDefaultFalse(goods);
        if (products == null || products.isEmpty()) {
            return new Vo(Collections.emptyList());
        }
        return new Vo(VO.toVOCollection(products, false));
    }

    @ApiOperation("新增产品")
    @PostMapping("product/add/{goodsId}")
    @RequiresPermissions("sys:good:productAdd")
    public VO productAdd(@RequestBody ProductRequest productRequest, @PathVariable @ApiParam(value = "商品id") Long goodsId)
            throws AdminException {
        Goods goods = dao.get(Goods.class, goodsId);
        if (goods == null) {
            throw new AdminException("未找到此商品");
        }

        Product product = new Product();
        product.setGoods(goods);
        product.setIsDefault(false);
        product.setCreateUser(shiroService.getUser());
        BeanUtils.copyProperties(productRequest, product, BeanNullUtil.getNullPropertyNames(productRequest));
        List<GoodSpecificationRequest> goodSpecificationRequests = productRequest.getGoodSpecificationListVo();
        StringBuffer goodSpecIds = new StringBuffer("");
        StringBuffer sku = new StringBuffer("");
        if (!goodSpecificationRequests.isEmpty()) {
            goodSpecificationRequests.forEach(goodSpecificationRequest -> {
                String specificationValue = goodSpecificationRequest.getValue();
                if (StringUtils.isBlank(specificationValue)) {
                    return;
                }
                specificationValue = specificationValue.trim();
                Long specificationId = goodSpecificationRequest.getId();
                Specification specification = dao.get(Specification.class, specificationId);
                GoodSpecification goodSpecification = new GoodSpecification();
                goodSpecification.setGoods(goods);
                goodSpecification.setSpecification(specification);
                goodSpecification.setValue(specificationValue);
                goodSpecIds.append(goodSpecificationRepository.save(goodSpecification).getId() + ",");
                sku.append(specification.getName() + ":" + goodSpecification.getValue() + ",");
            });
            product.setGoodSpecIds(goodSpecIds.substring(0, goodSpecIds.length() - 1));
            product.setSku(sku.substring(0, sku.length() - 1));
        }
        productRepository.save(product);
        goodsRepository.save(goods);
        return new Vo(HttpStatus.OK);
    }

    @ApiOperation("编辑产品")
    @PostMapping("product/update/{productId}")
    @RequiresPermissions("sys:good:productUpdate")
    public VO productUpdate(@RequestBody ProductRequest productRequest, @PathVariable @ApiParam(value = "产品id") Long
            productId) throws AdminException {
        Product product = dao.get(Product.class, productId);
        if (product == null) {
            throw new AdminException("未找到此产品");
        }
        if (productRequest.getGoodsNumber() != null) {
            Goods goods = product.getGoods();
            goodsRepository.save(goods);
        }
        String goodSpecIds = product.getGoodSpecIds();

        List<GoodSpecification> goodSpecifications = new ArrayList<>();
        if (StringUtils.isNotBlank(goodSpecIds)) {
            for (String s : goodSpecIds.split(",")) {
                GoodSpecification goodSpecification = goodSpecificationRepository.getOne(Long.parseLong(s));
                goodSpecifications.add(goodSpecification);
            }
            goodSpecificationRepository.deleteAll(goodSpecifications);
            product.setGoodSpecIds("");
        }

        BeanUtils.copyProperties(productRequest, product, BeanNullUtil.getNullPropertyNames(productRequest));
        product.setUpdateUser(shiroService.getUser());

        List<GoodSpecificationRequest> goodSpecificationRequests = productRequest.getGoodSpecificationListVo();

        StringBuffer newGoodSpecIds = new StringBuffer("");
        StringBuffer sku = new StringBuffer("");
        if (!goodSpecificationRequests.isEmpty()) {
            goodSpecificationRequests.forEach(goodSpecificationRequest -> {
                String specificationValue = goodSpecificationRequest.getValue();
                if (StringUtils.isBlank(specificationValue)) {
                    return;
                }
                specificationValue = specificationValue.trim();
                Long goodSpecificationId = goodSpecificationRequest.getId();
                Specification specification = dao.get(Specification.class, goodSpecificationId);
                GoodSpecification goodSpecification = new GoodSpecification();
                goodSpecification.setGoods(product.getGoods());
                goodSpecification.setSpecification(dao.get(Specification.class, goodSpecificationId));
                goodSpecification.setValue(specificationValue);
                newGoodSpecIds.append(goodSpecificationRepository.save(goodSpecification).getId() + ",");
                sku.append(specification.getName() + ":" + goodSpecification.getValue() + ",");
            });
            product.setGoodSpecIds(newGoodSpecIds.substring(0, newGoodSpecIds.length() - 1));
            product.setSku(sku.substring(0, sku.length() - 1));
        }
        productRepository.save(product);
        return new Vo(HttpStatus.OK);
    }

    @ApiOperation("删除产品")
    @PostMapping("product/delete/{productId}")
    @RequiresPermissions("sys:good:productDelete")
    public VO productDelete(@PathVariable @ApiParam(value = "产品id") Long productId) throws AdminException {
        Product product = dao.get(Product.class, productId);
        if (product == null) {
            throw new AdminException("未找到此产品");
        }
        Goods goods = product.getGoods();
        goodsRepository.save(goods);
        String goodSpecIds = product.getGoodSpecIds();
        List<GoodSpecification> goodSpecifications = new ArrayList<>();
        if (StringUtils.isNotBlank(goodSpecIds)) {
            for (String s : goodSpecIds.split(",")) {
                GoodSpecification goodSpecification = goodSpecificationRepository.getOne(Long.parseLong(s));
                goodSpecifications.add(goodSpecification);
            }
            goodSpecificationRepository.deleteAll(goodSpecifications);
            product.setGoodSpecIds("");
        }
        product.setDeleted(true);
        productRepository.save(product);
        return new Vo(HttpStatus.OK);
    }

    @ApiOperation("获取产品详细信息")
    @PostMapping("product/detail/{productId}")
    @RequiresPermissions("sys:goods:productDetail")
    public Vo<Product.Vo> productDetail(@PathVariable @ApiParam("产品id") Long productId) throws AdminException {
        Product product = dao.get(Product.class, productId);
        if (null == product) {
            throw new AdminException("产品不存在");
        }
        List<GoodSpecification> goodSpecifications = new ArrayList<>();
        if (StringUtils.isNotBlank(product.getGoodSpecIds())) {
            for (String s : product.getGoodSpecIds().split(",")) {
                GoodSpecification goodSpecification = goodSpecificationRepository.getOne(Long.parseLong(s));
                goodSpecifications.add(goodSpecification);
            }
        }
        Product.Vo productVo = (Product.Vo) product.toVO(false);
        productVo.setGoodSpecificationListVo((List<GoodSpecification.Vo>) VO.toVOCollection(goodSpecifications));
        return new Vo(productVo);
    }

    public void saveProduct(String sku, Long goodsStock, Goods goods) throws AdminException {
        GoodSpecification g = save(sku, goods);
        Product p = new Product();
        p.setGoods(goods);
        p.setGoodSpecIds(g.getSpecification().getId().toString());
        p.setMarketPrice(goods.getOriginalPrice());
        p.setPrice(goods.getPrice());
        p.setIsDefault(true);
        p.setSku(sku);
        Product save = productRepository.save(p);

        SysSection numberOne = sysSectionService.getNumberOne();
        if(goodsStock != null) {
            saveCenter(goods, save, numberOne, goodsStock);
        }
    }

    public GoodSpecification save(String sku, Goods goods) {
        Specification s = save(sku);
        GoodSpecification g = new GoodSpecification();
        g.setGoods(goods);
        g.setValue(sku);
        g.setSpecification(s);
        GoodSpecification goodSpecification = goodSpecificationRepository.save(g);
        return goodSpecification;
    }

    public Specification save(String sku) {
        Specification s = new Specification();
        s.setName(sku);
        Specification specification = specificationRepository.save(s);
        return specification;
    }

    //添加商品塞到商品门店关联表
    @Transactional(rollbackFor = Exception.class)
    public void saveCenter(Goods goods, Product product, SysSection section, Long num) throws AdminException {
        StockChangeRecord s = new StockChangeRecord();
        s.setOrg(section);
        s.setGoods(goods);
        s.setProduct(product);
        s.setChangeType(StockChangeRecord.ChangeType.adjust);
        s.setChangeDirection(StockChangeRecord.ChangeDirection.add);
        s.setNum(num);
        s.setStockStatus(StockChangeRecord.StockStatus.ApprovalSuccess);
        StockChangeRecord stockChangeRecord = orgStockChangeService.saveStockChangeRecord(s, goods, product, section, true);
    }

    @ApiOperation("批量新增商品属性")
    @PostMapping("attributes/addList/{goodsId}")
    @RequiresPermissions("sys:good:attributes:addList")
    public VO attributesAddList(@RequestBody List<AddGoodAttributes> addGoodAttributes, @PathVariable @ApiParam("商品id")
            Long goodsId) throws AdminException {
        Goods goods = dao.get(Goods.class, goodsId);
        if (null == goods) {
            throw new AdminException("商品不存在");
        }
        List<GoodAttributes> goodAttributes = new ArrayList<>(addGoodAttributes.size());
        for (AddGoodAttributes addGoodAttribute : addGoodAttributes) {
            GoodAttributes goodAttribute = new GoodAttributes();
            goodAttribute.setAttributes(attributesRepository.getOne(addGoodAttribute.attributesid));
            goodAttribute.setValue(addGoodAttribute.value);
            goodAttribute.setSortNo(addGoodAttribute.sortNo);
            goodAttribute.setGoods(goods);
            goodAttributes.add(goodAttribute);
        }
        goodAttributesRepository.saveAll(goodAttributes);
        return new Vo(HttpStatus.OK);
    }

    @ApiOperation("单个新增商品属性")
    @PostMapping("attributes/add/{goodsId}")
    @RequiresPermissions("sys:good:attributes:add")
    public VO attributesAdd(@RequestBody AddGoodAttributes addGoodAttributes, @PathVariable @ApiParam("商品id") Long
            goodsId) throws AdminException {
        Goods goods = dao.get(Goods.class, goodsId);
        if (null == goods) {
            throw new AdminException("商品不存在");
        }
        GoodAttributes goodAttribute = new GoodAttributes();
        goodAttribute.setAttributes(attributesRepository.getOne(addGoodAttributes.attributesid));
        goodAttribute.setValue(addGoodAttributes.value);
        goodAttribute.setSortNo(addGoodAttributes.sortNo);
        goodAttribute.setGoods(goods);
        goodAttributesRepository.save(goodAttribute);
        return new Vo(HttpStatus.OK);
    }

    @ApiModel("新增商品属性实体")
    class AddGoodAttributes {
        @ApiModelProperty("值")
        private String value;
        @ApiModelProperty("排序")
        private Long sortNo;
        @ApiModelProperty("属性id")
        Long attributesid;
    }

    @ApiOperation("删除商品属性")
    @PostMapping("attributes/del/{goodsAttributesId}")
    @RequiresPermissions("sys:good:attributes:del")
    public VO attributesDel(@PathVariable @ApiParam("商品属性id") Long goodsAttributesId) throws AdminException {
        GoodAttributes goodAttributes = dao.get(GoodAttributes.class, goodsAttributesId);
        if (null == goodAttributes) {
            throw new AdminException("商品属性不存在");
        }
        goodAttributesRepository.delete(goodAttributes);
        return new Vo(HttpStatus.OK);
    }

    @ApiOperation("编辑商品属性值")
    @PostMapping("attributes/del/{goodsAttributesId}/{value}")
    @RequiresPermissions("sys:good:attributes:edit")
    public VO attributesEdit(@RequestBody AddGoodAttributes addGoodAttributes, @PathVariable @ApiParam("商品属性id") Long
            goodsAttributesId) throws AdminException {
        GoodAttributes goodAttributes = dao.get(GoodAttributes.class, goodsAttributesId);
        if (null == goodAttributes) {
            throw new AdminException("商品属性不存在");
        }
        goodAttributes.setValue(addGoodAttributes.value);
        goodAttributes.setSortNo(addGoodAttributes.sortNo);
        goodAttributesRepository.save(goodAttributes);
        return new Vo(HttpStatus.OK);
    }


}
